package bpmjs;

import haxe.Timer;
import js.Lib;
import js.Dom;

using bpmjs.MooToolsAdapter;

class Stats {
	
	private static var initialized : Bool;
	private static var div : HtmlDom;
	private static var lastTime : Float;
	private static var fps : Float = 0;
	private static var times : Array<{start : Float, stop : Float, message : String}>;
	private static var finishedTimes : Array<{start : Float, stop : Float, message : String}>;
	private static var messages : Array<String>;
	
	public static function init(content : HtmlDom)
	{
		times = new Array();
		finishedTimes = new Array();
		messages = new Array();
		div = Lib.document.createDiv();
		div.setStyle("background", "#000000");
		div.setStyle("font-family", "Courier");
		div.setStyle("font-size", "12px");
		div.setStyle("color", "#00ff00");
		content.appendChild(div);
		
		initialized = true;
		
		var timer = new Timer(Math.round(1000 / 5));
		timer.run = handleRun;
	}
	
	public static function measureFPS()
	{
		checkInit();
		var time = Date.now().getTime();
		fps += (1000 / (time - lastTime) - fps) / 2;
		lastTime = time; 
	}
	
	public static function checkStart(message : String)
	{
		checkInit();
		var time = Date.now().getTime();
		times.push({start : time, stop : 0.0, message : message});
	}
	
	public static function addMessage(message : String)
	{
		checkInit();
		messages.push(message);
	}
	
	public static function checkStop()
	{
		checkInit();
		
		var timeAndMessage = times.pop();
		timeAndMessage.stop = Date.now().getTime();
		
		finishedTimes.push(timeAndMessage);
	}
	
	static function checkInit()
	{
		if (!initialized)
			init(Lib.document.body);
	}
	
	static function handleRun()
	{
		var finalMessages : Array<String> = new Array();
		
		finalMessages.push("FPS: " + Math.round(fps));
		
		for(timeAndMessage in finishedTimes)
		{
			finalMessages.push(" > " + timeAndMessage.message + ": " + (timeAndMessage.stop - timeAndMessage.start) + " ms");
			finishedTimes.remove(timeAndMessage);
		}
		
		for(message in messages)
		{
			finalMessages.push(message);
		}
		messages = new Array();
		
		div.innerHTML = finalMessages.join("<br>");
	}
}
